//
//  ShopViewController.m
//  Products_B
//
//  Created by lanou on 16/5/27.
//  Copyright © 2016年 朋学友. All rights reserved.
//

#import "ShopViewController.h"
#import "ShopCollectionViewCell.h"
#import "SmallShopCollectionViewCell.h"
#import "ShopModel.h"
#import "ShopCollectionReusableView.h"
#import "ShopDetailViewController.h"
#import "FooterCollectionReusableView.h"
#import "TopSecondViewController.h"
#import "ShipinViewController.h"
#import "TopModel.h"

#define kShopUrl @"http://api.izhangchu.com/"

@interface ShopViewController () <UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>

@property (nonatomic, strong) UICollectionView *bigCollectionView;
@property (nonatomic, strong) UILabel *label;
@property (nonatomic, strong) NSMutableArray *imageUrlArray;
@property (nonatomic, strong) NSMutableArray *shopModelArray;

@property (nonatomic, strong) ShopCollectionReusableView *headerView;
@property (nonatomic, assign) NSInteger total;
@property (nonatomic, assign) NSInteger page;

@end

@implementation ShopViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _page = 1;
    
    _imageUrlArray = [NSMutableArray array];
    _shopModelArray = [NSMutableArray array];
    self.navigationController.navigationBar.translucent = NO;
    
    self.navigationItem.title = @"商城";
    
    // 创建collectionView
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    _bigCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, kWidth, kHeight - 64) collectionViewLayout:flowLayout];
    _bigCollectionView.dataSource = self;
    _bigCollectionView.delegate = self;
    _bigCollectionView.backgroundColor = [UIColor colorWithRed:230 / 255.0 green:230 / 255.0 blue:230 / 255.0 alpha:1];
    [self.view addSubview:_bigCollectionView];
    
    // 注册
    [_bigCollectionView registerClass:[ShopCollectionViewCell class] forCellWithReuseIdentifier:@"shopCollectionViewCell"];
    
    // 注册_bigCollectionView的表头
    [_bigCollectionView registerClass:[ShopCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
    
    // 注册表尾
    [_bigCollectionView registerClass:[FooterCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footer"];
    
    [self requestShopData];
    
//    [self req];
}



// @{@"methodName":@"MallHomepageList",@"version":@4.3,@"page":@(_page),@"size":@10,@"user_id":@1513438,@"_time":@1464596319,@"_signature":@"7d69b7de76a8bdf08f5f05496d72a385"}
- (void)requestShopData {
    NSDictionary *parDic = @{@"methodName":@"MallHomepageList",@"version":@4.3,@"page":@(_page),@"size":@10,@"_time":@1464596319,@"_signature":@"7d69b7de76a8bdf08f5f05496d72a385"};
    [RequestManager requestWithUrl:kShopUrl requestType:RequestTypePOST parDic:parDic finish:^(NSData *data) {
        NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        NSLog(@" +++++++ %@",jsonDic);
        if (_page == 1) {
            _total = [jsonDic[@"data"][@"total"] integerValue];
        }

        NSMutableArray *tempArray = [ShopModel shopModelAnalyseDataWithJsonDic:jsonDic];
        [self.shopModelArray addObjectsFromArray:tempArray];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [_bigCollectionView reloadData];
        });
        
    } error:^(NSError *error) {
        NSLog(@" --- 请求数据失败");
    }];

}

- (void)req {
    
    NSDictionary *parDic = @{@"methodName":@"MallHomepage",@"version":@4.3,@"user_id":@0,@"_time":@"",@"_signature":@""};
    [RequestManager requestWithUrl:@"http://api.izhangchu.com/" requestType:RequestTypePOST parDic:parDic finish:^(NSData *data) {
    
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        NSLog(@".............. dic = %@",dic);
        _imageUrlArray = [TopModel topModelAnalyseDataWithJsonDic:dic];

    } error:^(NSError *error) {
        
    }];
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (collectionView != _bigCollectionView) {
        return _imageUrlArray.count;
    }
    NSLog(@"%ld",_shopModelArray.count);
    return self.shopModelArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (collectionView != _bigCollectionView) {
        SmallShopCollectionViewCell *smallCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"smallShopCollectionViewCell" forIndexPath:indexPath];
        smallCell.imageUrlString = self.imageUrlArray[indexPath.row];
        return smallCell;
    } else {
       ShopCollectionViewCell *bigCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"shopCollectionViewCell" forIndexPath:indexPath];
        bigCell.shopModel = self.shopModelArray[indexPath.row];
        return bigCell;
    }
}

#pragma mark - 点击cell的方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    ShopModel *model = self.shopModelArray[indexPath.row];
    if (collectionView == _bigCollectionView) {
        ShopDetailViewController *shopDetailVC = [[ShopDetailViewController alloc] init];
        shopDetailVC.id =  model.id;
        [self.navigationController pushViewController:shopDetailVC animated:YES];
    } else {
        ShipinViewController *shipinVC = [[ShipinViewController alloc] init];
        shipinVC.id = 12;
        [self.navigationController pushViewController:shipinVC animated:YES];
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (collectionView != _bigCollectionView) {
        return CGSizeMake(kWidth / 2 - 20, 360 * (kWidth / 2 - 20) / 640);
    
    } else {
        return CGSizeMake(kWidth / 2 - 7.5, kWidth / 2 - 7.5 + 120);
    }
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(5, 5, 5, 5);
}

// 列间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 5;
}

// 行间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 5;
}

// 返回表头
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if (collectionView == _bigCollectionView) {
        if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
            _headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header" forIndexPath:indexPath];
            // 表头的交互默认是关闭的
            _headerView.userInteractionEnabled = YES;
            _headerView.smallCollectionView.dataSource = self;
            _headerView.smallCollectionView.delegate = self;
            // 注册
            [_headerView.smallCollectionView registerClass:[SmallShopCollectionViewCell class] forCellWithReuseIdentifier:@"smallShopCollectionViewCell"];
            dispatch_async(dispatch_get_main_queue(), ^{
                [_headerView.smallCollectionView reloadData];
            });
            
            __block ShopViewController *blockSelf = self;
            _headerView.tapBlock = ^() {
                TopSecondViewController *topSecVC = [[TopSecondViewController alloc] init];
                topSecVC.id = 11;
                [blockSelf.navigationController pushViewController:topSecVC animated:YES];
            };
            
            return _headerView;
        }
        if ([kind isEqualToString:UICollectionElementKindSectionFooter]) {
             FooterCollectionReusableView *footer = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footer" forIndexPath:indexPath];
            [footer.button setTitle:[NSString stringWithFormat:@"还有%ld个热卖商品",_total] forState:UIControlStateNormal];
            [footer.button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
            return footer;
        }
    }
    return nil;
}

- (void)buttonAction:(UIButton *)button {
    _page += 1;
    _total -= 10;
    if (_total == 0) {
        return;
    }
    [self requestShopData];
}

// 返回表尾大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
    if (collectionView == _bigCollectionView) {
        return CGSizeMake(kWidth, 50);
    }
    return CGSizeMake(0, 0);
}

// 返回表头大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    if (collectionView == _bigCollectionView) {
      return CGSizeMake(kWidth, _headerView.label.frame.origin.y + _headerView.label.frame.size.height + 20);
    }
    return CGSizeMake(0, 0);
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
